package ownTemplates;

import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

/**
 * 〈一句话功能简述>
 * 〈〉
 *
 * @Author 17505
 * @Create 2021/6/4
 * @Since 1.0.0
 */
public class AlgoVisualizer {
    private Circle[] circles;
    private AlgoFrame algoFrame;
    private boolean isAnimate = true;

    public AlgoVisualizer(int sceneWidth, int sceneHeight, int N) {
        int R = 50;
        circles = new Circle[N];
        for (int i = 0; i < N; i++) {
            int x = (int) (Math.random() * (sceneWidth - 2 * 50)) + R;
            int y = (int) (Math.random() * (sceneHeight - 2 * 50)) + R;
            int vx = (int) (Math.random() * 11) - 5;
            int vy = (int) (Math.random() * 11) - 5;
            circles[i] = new Circle(x, y, R, vx, vy);
        }

        EventQueue.invokeLater(() -> {
            algoFrame = new AlgoFrame("Welcome", sceneWidth, sceneHeight);
            algoFrame.addKeyListener(new AlgoKeyListener());
            algoFrame.addMouseListener(new AlgoMouseListener());
            new Thread(() -> {
                while (true) {
                    run();
                }
            }).start();

        });
    }

    private void run() {
        while (true) {
            // 绘制数据
            algoFrame.render(circles);
            AlgoVisHelper.pause(20);
            if (isAnimate)
            // 更新数据
            for (Circle circle : circles) {
                circle.move(0, 0, algoFrame.getCanvasWidth(), algoFrame.getCanvasHeight());
            }
        }
    }

    /** 与键盘交互的类  */
    private class AlgoKeyListener extends KeyAdapter {
        @Override
        public void keyReleased(KeyEvent e) {
            super.keyReleased(e);
            if (e.getKeyChar() == ' ') {
                isAnimate = !isAnimate;
            }
        }
    }

    /** 与鼠标的交互  */
    private class AlgoMouseListener extends MouseAdapter {
        @Override
        public void mousePressed(MouseEvent event) {
            super.mousePressed(event);
            event.translatePoint(0, -(algoFrame.getBounds().height - algoFrame.getCanvasHeight()));
            for (Circle circle : circles) {
                if (circle.contain(event.getPoint())) {
                    circle.isFilled = !circle.isFilled;
                }
            }
            //System.out.println(event.getPoint());
        }
    }

    public static void main(String[] args) {
        int sceneWidth = 800;
        int sceneHeight = 800;
        int N = 10;
        AlgoVisualizer visualizer = new AlgoVisualizer(sceneWidth, sceneHeight, N);
    }
}